import * as comm from './../../utils/common';
const storageService = require('../../services/storage')

// 获取 App 实例
const appInstance = getApp();
Component({
  options: {
    multipleSlots: true // 在组件定义时的选项中启用多slot支持
  },
  /**
   * 组件的属性列表
   */
  properties: {
    did: {
      type: String,
      value: ''
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    //did: null,
    updownCfg: {},
    deviceCfg: {},
    longtap: false,
    showWithInput: false,
    modeName: "",
    switchVal: false,
    minutePickerVisible: false,
    minutePickerVal: "00:00",
    timeType: 0,
    begTime: "08:00",
    endTime: "18:00",
    updownTimeVisible: false,
    updownTimeValue: 30,
    updownTimeLabel: "30分钟",
    updownTimes: [{
        label: '0分钟',
        value: 0
      },
      {
        label: '15分钟',
        value: 15
      },
      {
        label: '30分钟',
        value: 30
      },
      {
        label: '1小时',
        value: 60
      },
      {
        label: '2小时',
        value: 120
      },
    ],
    popSyncToDeviceConfirmVisible: false,
  },
  lifetimes: {
    attached() {
      console.log("attached....................updown");
      let dobj = storageService.getDeviceInfo(this.data.did)
      this.data.deviceCfg = dobj;
      this.getAndInitChs();
    },
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getAndInitChs() {
      let updownCfg = storageService.getUpdownCfg(this.data.did)
      if (comm.isEmptyObj(updownCfg)) {
        let chCfg = storageService.getDeviceChannels(this.data.did)
        updownCfg = {
          sel: 0,
          modes: [{
              "nm": "模式一",
              "cls": [],
              "beg": "08:00",
              "end": "18:00",
              "tm": 30
            },
            {
              "nm": "模式二",
              "cls": [],
              "beg": "08:00",
              "end": "18:00",
              "tm": 30
            }, {
              "nm": "模式三",
              "cls": [],
              "beg": "08:00",
              "end": "18:00",
              "tm": 30
            }
          ]
        };
        for (var j = 0; j < updownCfg.modes.length; j++) {
          let cls = updownCfg.modes[j].cls;
          for (var i = 0; i < chCfg.length; i++) {
            if (chCfg[i].u == 0) {
              continue;
            }
            cls.push({
              "n": chCfg[i].n,
              "nm": chCfg[i].nm,
              "c": chCfg[i].c,
              "v": 0
            });
          }
        }
        storageService.saveUpdownCfg(this.data.did, updownCfg)
      }
      this.setData({
        updownCfg: JSON.parse(JSON.stringify(updownCfg)),
        begTime: updownCfg.modes[updownCfg.sel].beg,
        endTime: updownCfg.modes[updownCfg.sel].end,
        updownTimeValue: [updownCfg.modes[updownCfg.sel].tm],
        updownTimeLabel: this.getUpdownTimeLabel(updownCfg.modes[updownCfg.sel].tm)
      });
      console.log(this.data.updownCfg);
    },
    sliderChange(e) {
      if (this.valChange(e)) {
        storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)
      }
    },
    sliderChangeing(e) {
      this.valChange(e);
    },
    steppperChange(e) {
      if (this.valChange(e)) {
        storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)
      }
    },
    valChange(e) {
      const {
        value
      } = e.detail;
      let idx = e.currentTarget.dataset.idx;
      let str = "updownCfg.modes[" + this.data.updownCfg.sel + "].cls[" + idx + "].v";
      this.setData({
        [str]: value
      });
      return true;
    },
    selMode(e) {
      if (this.data.longtap) {
        this.data.longtap = false;
        return;
      }
      let idx = e.currentTarget.dataset.idx;
      if (this.data.updownCfg.sel == idx) {
        return;
      }
      this.setData({
        "updownCfg.sel": idx
      });
      storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)
      this.getAndInitChs();
    },
    editModeName() {
      this.data.longtap = true;
      this.setData({
        showWithInput: true,
        modeName: this.data.updownCfg.modes[this.data.updownCfg.sel].nm
      });
    },
    editConfirm() {
      if (comm.isEmpty(this.data.modeName)) {
        this.showToast("名称不能为空!");
        this.setData({
          modeName: this.data.updownCfg.modes[this.data.updownCfg.sel].nm
        });
        return;
      }
      let str = "updownCfg.modes[" + this.data.updownCfg.sel + "].nm";
      this.setData({
        [str]: this.data.modeName
      });
      storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)
      this.closeDialog();
    },
    closeDialog() {
      this.setData({
        showWithInput: false
      });
    },
    bindKeyInput: function (e) {
      let val = e.detail.value;
      if (comm.isEmpty(val)) {
        val = "";
      }
      this.setData({
        modeName: val
      })
    },
    showDatePicker(event) {
      let type = parseInt(event.currentTarget.dataset.type);
      this.setData({
        timeType: type,
        minutePickerVal: type == 0 ? this.data.begTime : this.data.endTime,
        minutePickerVisible: true
      });
    },
    hideDatePicker() {
      this.setData({
        minutePickerVisible: false
      });
    },
    pickerDateConfirm(e) {
      const {
        value
      } = e.detail;
      if (this.data.minutePickerVal == value) {
        return;
      }
      let str = "updownCfg.modes[" + this.data.updownCfg.sel + "].";
      if (this.data.timeType == 0) {
        str += "beg";
        this.setData({
          [str]: value,
          begTime: value
        });
      } else {
        str += "end";
        this.setData({
          [str]: value,
          endTime: value
        });
      }
      storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)

      this.hideDatePicker();
    },
    showTimePicker() {
      this.setData({
        updownTimeVisible: true
      });
    },
    updownTimePickerChange(e) {
      const {
        value
      } = e.detail;
      if (this.data.updownTimeValue == value) {
        return;
      }
      let str = "updownCfg.modes[" + this.data.updownCfg.sel + "].tm";
      this.setData({
        [str]: value[0],
        updownTimeValue: value,
        updownTimeLabel: this.getUpdownTimeLabel(value)
      });
      storageService.saveUpdownCfg(this.data.did, this.data.updownCfg)
      this.updownTimePickerCancel();
    },
    updownTimePickerCancel() {
      this.setData({
        updownTimeVisible: false
      });
    },
    getUpdownTimeLabel(value) {
      if (Array.isArray(value)) {
        value = value[0];
      }
      let label = "";
      for (var i = 0; i < this.data.updownTimes.length; i++) {
        if (value == this.data.updownTimes[i].value) {
          label = this.data.updownTimes[i].label;
          break;
        }
      }
      return label;
    },
    syncToDevice() {
      let cls = this.data.updownCfg.modes[this.data.updownCfg.sel].cls;
      let flag = 0;
      for (var i = 0; i < cls.length; i++) {
        if (cls[i].v > 0) {
          flag = 1;
          break;
        }
      }
      if (flag == 0) {
        this.showToast("没有数据需要同步!");
        return;
      }
      let btArr = this.data.begTime.split(":");
      let etArr = this.data.endTime.split(":");
      if ((parseInt(etArr[0]) * 60 + parseInt(etArr[1])) - (parseInt(btArr[0]) * 60 + parseInt(btArr[1])) <= parseInt(this.data.updownTimeValue) * 2) {
        this.showToast("开关灯时间不足以执行日出日落!");
        return;
      }

      this.setData({
        popSyncToDeviceConfirmVisible: true
      });
    },
    closePopSyncToDeviceDialog() {
      this.setData({
        popSyncToDeviceConfirmVisible: false
      });
    },
    confirmPopSyncToDeviceDialog() {
      this.closePopSyncToDeviceDialog();
      const $t = this;
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          let btArr = $t.data.begTime.split(":");
          let etArr = $t.data.endTime.split(":");
          let tm = parseInt($t.data.updownTimeValue);
          let btH = parseInt(btArr[0]);
          let btM = parseInt(btArr[1]);
          let etH = parseInt(etArr[0]);
          let etM = parseInt(etArr[1]);
          let tmH = parseInt(tm / 60);
          let tmM = tm % 60;
          let btH2 = btH + tmH;
          let btM2 = btM + tmM;
          if (btM >= 60) {
            btM2 = btM2 - 60;
            btH2++;
          }
          let etH2 = etH - tmH;
          let etM2 = etM - tmM;
          if (etM2 < 0) {
            etM2 = etM2 + 60;
            etH2--;
          }

          let chCfg = storageService.getDeviceChannels($t.data.did)
          let cls = $t.data.updownCfg.modes[$t.data.updownCfg.sel].cls;
          let tl = [];
          for (var i = 0; i < chCfg.length; i++) {
            if (chCfg[i].u == 0) {
              tl.push([]);
              continue;
            }
            let exists = false;
            for (var j = 0; j < cls.length; j++) {
              if (chCfg[i].n == cls[j].n) {
                if (cls[j].v == 0) {
                  break;
                }
                exists = true;
                let arr = [];
                arr.push([(btH * 100 + btM) * 100, 0]);
                arr.push([(btH2 * 100 + btM2) * 100, cls[j].v]);
                arr.push([(etH2 * 100 + etM2) * 100, cls[j].v]);
                arr.push([(etH * 100 + etM) * 100, 0]);
                tl.push(arr);
                break;
              }
            }
            if (!exists) {
              tl.push([]);
            }
          }
          appInstance.sendMtMsg($t.data.deviceCfg.topicSend, "syncDataUp", {
            "t": 3,
            "s": $t.data.updownCfg.sel,
            "n": $t.data.updownCfg.modes[$t.data.updownCfg.sel].nm,
            "tl": tl
          });
          $t.data.timeoutObj = setTimeout(function () {
            $t.confirmPopSyncToDeviceDialogResult(0);
          }, 5000);
        }
      });
    },
    confirmPopSyncToDeviceDialogResult(succ) {
      const $t = this;
      wx.hideLoading();
      if (succ == 0) {
        $t.showToast("请求响应超时...");
      } else {
        $t.showToast("同步成功!");
        this.triggerEvent('setTitle', {
          type: 3,
          title: $t.data.updownCfg.modes[$t.data.updownCfg.sel].nm
        });
        clearTimeout($t.data.timeoutObj);
      }
    },






    showToast(msg) {
      // 子组件中
      this.triggerEvent('showToast', {
        msg: msg
      });
    },

  },
})